<template>
  <div class="user-container" v-loading="loading">
    <el-card>
      <template #header>
        <div class="header">
          <span>用户列表</span>
          <el-button type="primary" @click="handleAdd">添加用户</el-button>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="头像" width="100">
          <template #default="{ row }">
            <el-avatar :src="row.cover" :size="40" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '可用' : '不可用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ctime" label="创建时间" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="头像" prop="cover">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.cover" :src="form.cover" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { request } from '../../composables/useCommon'

// 表格数据
const tableData = ref([])

// 表格 loading 状态
const loading = ref(false)

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const res = await request('ragUser/', 'get', {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value
    })
    tableData.value = res.records
    total.value = res.total
  } catch (err) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 新增用户
const addUser = async (userData) => {
  try {
    await request('ragUser/', 'post', userData)
    ElMessage.success('用户添加成功')
    getTableData()
  } catch (err) {
    ElMessage.error('添加用户失败')
  }
}

// 修改用户
const updateUser = async (userData) => {
  try {
    await request('ragUser/', 'put', userData)
    ElMessage.success('用户更新成功')
    getTableData()
  } catch (err) {
    ElMessage.error('更新用户失败')
  }
}

// 删除用户
const deleteUser = async (userId) => {
  try {
    await request(`ragUser/${userId}`, 'delete')
    ElMessage.success('用户删除成功')
    getTableData()
  } catch (err) {
    ElMessage.error('删除用户失败')
  }
}

// 搜索
const searchQuery = ref('')
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  password: '',
  phone: '',
  cover: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  cover: [
    { required: true, message: '请上传头像', trigger: 'blur' }
  ]
}

// 处理添加用户
const handleAdd = () => {
  dialogTitle.value = '添加用户'
  form.id = ''
  form.name = ''
  form.password = ''
  form.phone = ''
  form.cover = ''
  form.status = 1
  dialogVisible.value = true
}

// 处理编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该用户吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteUser(row.id)
    } catch (err) {
      ElMessage.error('删除失败')
    }
  })
}

// 处理状态变更
const handleStatusChange = async (row) => {
  try {
    await updateUser({ id: row.id, status: row.status === 1 ? 0 : 1 })
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    row.status = row.status === 1 ? 0 : 1
  } catch (err) {
    ElMessage.error(`${row.status === 1 ? '禁用' : '启用'}失败`)
  }
}

// 处理头像上传成功
const handleAvatarSuccess = (response) => {
  form.cover = response.url
}

// 处理表单提交
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (form.id) {
        updateUser(form)
      } else {
        addUser(form)
      }
      dialogVisible.value = false
    }
  })
}

// 获取表格数据
getTableData()
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
